<template>
  <a-button
    type="link"
    style="padding: 4px 6px"
    @click="onClick"
    :loading="loading"
    :disabled="loading"
  >
    {{ editing ? '保存' : '编辑' }}
  </a-button>
</template>
<script setup>
import { computed } from 'vue'
import { useVModel } from '@vueuse/core'
import { updateStructTable, addStructTable } from '@/api/db.js'
import { message as Message } from 'ant-design-vue'
// import { Form, message as Message } from 'ant-design-vue'
// import {
//   useDataSourceManager,
//   useDataSource,
//   useGroupId,
//   useLockForInUse,
// } from './provide-context.js'
// import { createFolder, updateFileInfo } from '@/api/db.js'
// import { useDbType } from './provide-context.js'
/**
 * 外部参数
 */
let props = defineProps({
  editing: { type: Boolean, default: () => false },
  loading: { type: Boolean, default: () => false },
  data: { type: Object, required: true },
  tableId: { type: String, required: true },
  isAdding: {
    type: Boolean,
    required: true,
  },
})
/**
 * 事件定义
 */
let emit = defineEmits([
  'update:editing',
  'update:loading',
  'updata:isAdding',
  'submit',
])
/**
 * 双向绑定
 */
let editing = useVModel(props, 'editing', emit)
let loading = useVModel(props, 'loading', emit)
let isAdding = useVModel(props, 'isAdding', emit)
// /**
//  * 全局
//  */
// let { update } = useDataSourceManager()
// let dataSource = useDataSource()
// let groupId = useGroupId()
// let lockForInUse = useLockForInUse()
// /**
//  * 校验相关
//  */
// let useForm = Form.useForm
// let { validate } = useForm(props.data, props.rules)
// /**
//  * 整体有没有在编辑状态
//  */
// let hasEditing = computed(() =>
//   dataSource.value.some(({ editing }) => editing === true),
// )
// /**
//  * 锁标识
//  */
// let lockSymbol = Symbol('edit')
/**
 * 操作事件
 */
// let dbType = useDbType()
async function onClick() {
  if (editing.value) {
    loading.value = true
    let data = {}
    let hasNull = false
    Object.keys(props.data).forEach(key => {
      if (key.startsWith('row')) {
        let value = props.data[key]
        if (value === '' || value === null || value === undefined) {
          hasNull = true
        }
        data[key.replace('row', '')] = value
      }
    })
    if (hasNull) {
      Message.error('数据不完整')
      loading.value = false
      return
    }
    try {
      if (!props.data.id) {
        await addStructTable({
          tableData: JSON.stringify(data),
          tableInfoId: props.tableId,
        })
        isAdding.value = false
      } else {
        await updateStructTable({
          tableData: JSON.stringify(data),
          id: props.data.id,
        })
      }
      editing.value = false
      emit('submit')

      Message.success(`保存成功`)
    } catch (e) {
      Message.error(`保存失败${e.message}`)
    }
    loading.value = false
  } else {
    editing.value = true
  }
}
</script>
